package com.ruoyi.weixin.controller;

import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.annotation.InnerAuth;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpMessageRouter;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.kefu.WxMpKefuMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 任务Controller
 *
 * @author jiandan
 * @date 2024-06-27
 */
@RestController
@RequestMapping("wx")
public class WxController extends BaseController {
    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private WxMpMessageRouter wxMpMessageRouter;

    @PostMapping(value = "", produces = "application/xml; charset=UTF-8")
    public String handleMessage(@RequestBody String requestBody,
                                @RequestParam("signature") String signature,
                                @RequestParam("timestamp") String timestamp,
                                @RequestParam("nonce") String nonce) {
        logger.info("handleMessage调用");
        // 校验消息是否来自微信
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            throw new IllegalArgumentException("非法请求，可能属于伪造的请求！");
        }
        // 解析消息体，封装为对象
        WxMpXmlMessage inMessage = WxMpXmlMessage.fromXml(requestBody);
        WxMpXmlOutMessage outMessage;
        try {
            // 将消息路由给对应的处理器，获取响应
            outMessage = wxMpMessageRouter.route(inMessage);
        } catch (Exception e) {
            logger.error("微信消息路由异常", e);
            outMessage = null;
        }
        // 将响应消息转换为xml格式返回
        return outMessage == null ? "" : outMessage.toXml();
    }

    @InnerAuth
    @PostMapping(value = "/wxMpKefuMessage")
    public AjaxResult sendKefuMessage(@RequestParam("toUser") String toUser,
                                @RequestParam("content") String content) {
        logger.info("sendKefuMessage调用");
        AjaxResult ajaxResult = toAjax(1);
        // 解析消息体，封装为对象
        WxMpKefuMessage message = WxMpKefuMessage.TEXT().toUser(toUser).content(content).build();
        try {
            // 将消息路由给对应的处理器，获取响应
            boolean rs = wxMpService.getKefuService().sendKefuMessage(message);

            if(rs){
                ajaxResult.put("msg","发送微信客服消息成功");
            }
        } catch (Exception e) {
            logger.error("微信消息路由异常", e);
            ajaxResult.put("msg","发送微信客服消息异常");
        }
        // 将响应消息转换为xml格式返回
        return ajaxResult;
    }

    /**
     * 查询任务列表
     */
    @GetMapping("")
    public String wx(String signature, String timestamp, String nonce, String echostr)
            throws WxErrorException {
        System.out.println("signature:" + signature + ",timestamp:" + timestamp + ",nonce:" + nonce
                + ",echostr:" + echostr);
        if (!wxMpService.checkSignature(timestamp, nonce, signature)) {
            // 消息签名不正确，说明不是公众平台发过来的消息
            return null;
        }
//        String accessToken = this.mpService.getAccessToken();
//        System.out.println("accessToken:"+accessToken);
        return echostr;
    }

}
